import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/model/address.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/address_add.dart';

class AddressManagePage extends StatefulWidget {
  bool isSelectAddress = false;

  AddressManagePage(this.isSelectAddress);

  @override
  State<StatefulWidget> createState() {
    return AddressManagePageState(isSelectAddress);
  }
}

class AddressManagePageState extends State<AddressManagePage> {
  List<Address> _addressList;
  int _currentIndex;

  bool isSelectAddress = false;

  AddressManagePageState(this.isSelectAddress);

  @override
  void initState() {
    super.initState();
    _getAddresses();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createAppBar(),
      body: ListView.builder(
        itemCount: _addressList == null ? 0 : _addressList.length,
        itemBuilder: (context, index) {
          Address address = _addressList[index];

          return Slidable(
            delegate: SlidableDrawerDelegate(),
            actionExtentRatio: 0.25,
            child: GestureDetector(
              onTap: () {
                if (isSelectAddress) {
                  Navigator.of(context).pop(address);
                } else {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return AddressAddPage(address: address);
                  })).then((value) {
                    _getAddresses();
                  });
                }
              },
              child: Container(
                color: Colors.white,
                padding:
                    const EdgeInsets.only(left: 10.0, right: 10.0, top: 15.0),
                child: Column(children: <Widget>[
                  Row(
                    children: <Widget>[
                      Text(
                        address.sendee != null && address.sendee.isNotEmpty
                            ? address.sendee
                            : "",
                        style: TextStyle(
                            fontSize: 20.0,
                            color: ColorCommon.black1,
                            fontWeight: FontWeight.bold),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20.0),
                        child: Text(
                          address.phone != null && address.phone.isNotEmpty
                              ? address.phone
                              : "",
                          style: TextStyle(
                              fontSize: 20.0,
                              color: ColorCommon.black1,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      address.isDefault
                          ? Container(
                              margin: const EdgeInsets.only(left: 10.0),
                              child: _getTagView("默认", ColorCommon.primaryColor),
                            )
                          : Container(),
                      // Container(
                      //   margin: const EdgeInsets.only(left: 10.0),
                      //   child: _getTagView("公司", Colors.blue),
                      // ),
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(address.province != null &&
                                address.city != null &&
                                address.district != null &&
                                address.address != null
                            ? (address.province +
                                address.city +
                                address.district +
                                address.address)
                            : ""),
                      ),
                      GestureDetector(
                        onTap: () {},
                        child: Icon(Icons.edit),
                      ),
                    ],
                  ),
                  Container(
                    color: ColorCommon.grey5,
                    margin: const EdgeInsets.only(top: 15.0),
                    height: 1.0,
                  ),
                ]),
              ),
            ),
            secondaryActions: <Widget>[
              IconSlideAction(
                caption: '删除',
                color: Colors.red,
                icon: Icons.delete,
                onTap: () {
                  _currentIndex = index;
                  _deleteAddress(address.id);
                },
              ),
            ],
          );
        },
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("我的地址"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            Navigator.of(context).pushNamed("/address_add").then((value) {
              _getAddresses();
            });
          },
          child: Container(
            child: Text("新建地址"),
            alignment: Alignment.center,
            padding: const EdgeInsets.only(right: 15.0),
          ),
        ),
      ],
    );
  }

  _getTagView(String tag, Color bgColor) {
    return new Container(
      height: 20.0,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 10.0, right: 10.0),
      decoration: new BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(100.0),
      ),
      child: new Text(
        tag,
        style: new TextStyle(fontSize: 12.0, color: Colors.white),
      ),
    );
  }

  _getAddresses() {
    NetUtil.get(
      context,
      Api.addresses,
      (data, message) {
        if (!mounted) return;
        setState(() {
          _addressList = (data as List)
              ?.map((e) => e == null ? null : Address.fromJson(e))
              ?.toList();
        });
      },
    );
  }

  _deleteAddress(int id) {
    NetUtil.delete(context, Api.addresses + "/" + id.toString(),
        (data, message) {
      ToastUtil.showMessageToast(message);

      if (!mounted) return;
      setState(() {
        _addressList.removeAt(_currentIndex);
      });
    });
  }
}
